package com.mathdroid.gui.main;

import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;

import com.mathdroid.model.Model;

/**
 * This Popup is an always on top frame, but is undecorated. It looks like
 * a simple context menu and has a simple black 1px border.
 * <b>Do not forget</b> to call pack and setVisible.
 */
public abstract class Popup extends JFrame {
	/**
	 * Default UID.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * The content panel.
	 */
	private JPanel panel = new JPanel();
	
	/**
	 * If this frame should be in the center of the DroidFrame.
	 */
	private boolean centerThisFrame = false;
	
	/**
	 * The layout constraints.
	 */
	private GridBagConstraints constraints = new GridBagConstraints();
	
	/**
	 * Create a popup aligned to the center of the DroidFrame.
	 */
	public Popup() {
		this.build();
		this.centerThisFrame = true;
	}

	/**
	 * Build this JFrame.
	 */
	private void build() {
		this.panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		this.panel.setLayout(new GridBagLayout());
		this.add(this.panel);
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.setUndecorated(true);
		this.setAlwaysOnTop(true);
	}

	/**
	 * Create a popup aligned to the component.
	 * @param parent The component to align this popup to.
	 */
	public Popup(final Component parent) {
		this.setLocation(
			(int) (parent.getLocationOnScreen().getX()), 
			(int) (parent.getLocationOnScreen().getY()));
		
		this.build();
	}
	
	

	/**
	 * Get the content panel.
	 * @return Content panel.
	 */
	public final JPanel getPanel() {
		return this.panel;
	}
	
	/**
	 * Get the layout constraints.
	 * @return Layout constraints.
	 */
	public final GridBagConstraints getConstraints() {
		return this.constraints;
	}
	
	@Override
	public final void pack() {
		super.pack();
		
		if (this.centerThisFrame) {
			DroidFrame f = Model.getDroidFrame();
			final int x = (int) (f.getLocation().getX() + f.getWidth() / 2 
					- this.getWidth() / 2);
			final int y = (int) (f.getLocation().getY() + f.getHeight() / 2 
					- this.getHeight() / 2);
			
			this.setLocation(x, y);
		}
	}
}
